<template>
  <!-- 功率曲线 -->
  <div class="chartContent">
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
      class="chartForm"
    >
      <a-form-item label="">
        <a-radio-group
          v-model:value="chartType"
          @change="changeChartType"
          :disabled="chartLoading"
        >
          <a-radio-button value="normal">功率曲线</a-radio-button>
          <a-radio-button value="total">总功率曲线</a-radio-button>
          <a-radio-button value="point" v-if="isShowPoint"
            >计量点曲线</a-radio-button
          >
        </a-radio-group>
      </a-form-item>
      <a-form-item label="日期">
        <a-date-picker
          v-model:value="form.date1"
          placeholder="选择日期"
          class="formSelect"
          formatter="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :allowClear="false"
        />
        <a-date-picker
          v-model:value="form.date2"
          placeholder="选择日期"
          class="formSelect"
          formatter="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          v-if="chartType !== 'point'"
          :disabledDate="
            (current) => current && current.valueOf() >= Date.now() - 8.64e6
          "
        />
      </a-form-item>
      <a-button
        type="primary"
        class="filterBtn"
        @click="getPowerChartData"
        :loading="chartLoading"
        >查询</a-button
      >
      <a-button
        type="primary"
        class="filterBtn yellowBtn"
        @click="checkData"
        v-hasPermission="'monitorPowerCheckData'"
        v-if="chartType !== 'point'"
      >
        查看数据</a-button
      >
    </a-form>
    <a-spin :spinning="chartLoading">
      <div
        v-for="(chartData, index) in chartsData"
        :key="index"
        :id="`powerChart${index}`"
        class="chartContainer"
      />
      <a-empty
        v-if="!chartsData?.length"
        style="opacity: 0.5; margin-top: 50px"
      />
    </a-spin>
  </div>

  <!-- 查看数据 -->
  <DetailsData
    :detailsDataVisible="detailsDataVisible"
    :chartsTableData="chartsTableData"
    :chartType="chartType"
    :branchData="branchData"
    @update:detailsDataVisible="(val) => (detailsDataVisible = val)"
  />
</template>
<script setup>

import DetailsData from "./detailsData.vue";
import * as echarts from "echarts";
import {
  chartOption,
  userChartOption,
  pointChartOption,
  brandChartOption,
} from "./chartOption";
import { getCurrentDate } from "@/utils/common";

import { cloneDeep } from "lodash-es";
const props = defineProps({
  stationInfo: {
    type: Number,
  },
});
const $api = inject("$api");
const detailsDataVisible = ref(false);
const form = ref({
  date1: null,
  date2: null,
});
const chartType = ref("normal");
const chartLoading = ref(false);
const chartsData = ref([]);
const chartsTableData = ref([]);
const chartOptionData = ref();
const pointChartOptionData = ref();
//处理y轴显示
let max2 = [];
let maxNum = null;
// 处理需量和Y轴计算
const processChartDemand = (chartData, powerChart, maxNum, max2) => {
  if (chartData.demand != "未设置需量") {
    powerChart.series[1].markLine.data[0].name = "需量值";
    powerChart.series[1].markLine.data[0].yAxis = chartData.demand;
    let num = chartData.demand || maxNum;
    let count = 1;
    while (num != 0) {
      count = count * 10;
      num = parseInt(num / 10);
    }

    count = count / 10;
    let maxY = maxNum;
    let arrMax = [];
    max2.map((item) => {
      if (chartData.demand) {
        arrMax.push(
          item >= chartData.demand
            ? Math.ceil(maxY / count) * count
            : Math.ceil(chartData.demand / count) * count
        );
      } else arrMax.push(Math.ceil(maxY / count) * count);
    });
    if (maxNum < chartData.demand) {
      powerChart.yAxis[0].max = chartData.demand;
    } else {
      powerChart.yAxis[0].max = Math.ceil(Math.max(...arrMax));
    }
  } else {
    powerChart.series[1].markLine.data[0].name = "未设置最大需量";
    powerChart.series[1].markLine.data[0].yAxis = 0;
  }
};

// 处理总需量和Y轴计算
const processChartTotalDemand = (chartData, pointChart, maxNum, max2) => {
  if (chartData.totaldemand != "未设置总需量") {
    pointChart.series[0].markLine.data[0].yAxis = chartData.totaldemand;
    let num = chartData.totaldemand || maxNum;
    let count = 1;
    while (num != 0) {
      count = count * 10;
      num = parseInt(num / 10);
    }

    count = count / 10;
    let maxY = maxNum;
    let arrMax = [];
    max2.map((item) => {
      if (chartData.totaldemand) {
        arrMax.push(
          item >= chartData.totaldemand
            ? Math.ceil(maxY / count) * count
            : Math.ceil(chartData.totaldemand / count) * count
        );
      } else arrMax.push(Math.ceil(maxY / count) * count);
    });
    if (maxNum < chartData.totaldemand) {
      pointChart.yAxis[0].max = chartData.totaldemand;
    } else {
      pointChart.yAxis[0].max = Math.ceil(Math.max(...arrMax));
    }
  } else {
    pointChart.series[0].markLine.data[0].name = "未设置最大总需量";
    pointChart.series[0].markLine.data[0].yAxis = 0;
  }
};
// 处理图表数据
const processChartData = (chart, chartData, lineType, isPowerChart = true) => {
  const seriesIndex = isPowerChart
    ? lineType !== 10
      ? lineType - 1
      : 4
    : lineType - 5;
  if (chart.series[seriesIndex]) {
    chart.series[seriesIndex].data = chartData?.lineData.map((item) => {
      const value = Number(item.value);
      if (!isNaN(value) && (isPowerChart ? lineType !== 4 : true)) {
        max2.push(value);
      }
      return {
        ...item,
        value: value,
      };
    });
  }
  return chart;
};
const powerChart = ref([]);
const pointChart = ref([]);
// 初始化图表
const initChart = (chartData, index, lineType) => {
  const xAxisData = chartData.lineData.map(
    (item) => item.dateTime.split(" ")[1]
  );
  if (chartType.value !== "point") {
    processChartData(powerChart.value[index], chartData, lineType);
    maxNum = max2.length > 0 ? Math.max(...max2) : 0;
    processChartDemand(chartData, powerChart.value[index], maxNum, max2);
    powerChart.value[index].xAxis[0].data = xAxisData;
    powerChart.value[index].xAxis[1].data = xAxisData;
    let chartName =
      chartType.value === "total" || chartType.value === "point"
        ? `${props.stationInfo.name}-总功率曲线`
        : chartData.stationTfName;
    powerChart.value[index].title.text = chartName;
  } else {
    processChartData(pointChart.value[index], chartData, lineType, false);
    maxNum = max2.length > 0 ? Math.max(...max2) : 0;
    processChartTotalDemand(chartData, pointChart.value[index], maxNum, max2);
    pointChart.value[index].xAxis[0].data = xAxisData;
    pointChart.value[
      index
    ].title.text = `${props.stationInfo.name}${chartData.linkName}-计量点功率曲线`;
  }
};
//查看是否存在计量点
const isShowPoint = ref(false);
const checkPoint = async () => {
  const params = {
    stationId: props.stationInfo.id,
  };
  const res = await $api.containPoint(params);
  if (res?.data) {
    isShowPoint.value = true;
    getTotLDemand();
  } else {
    isShowPoint.value = false;
  }
};
//需量查询
const linkDemandList = ref([]);
const getDemand = async () => {
  const res = await $api.checkLinkDemand({ stationId: props.stationInfo.id });
  if (res?.data) {
    linkDemandList.value = res.data;
  } else {
    linkDemandList.value = [];
  }
};
//总需量查询
const totalDemandList = ref([]);
const getTotLDemand = async () => {
  const res = await $api.checkTotalDemand({ stationId: props.stationInfo.id });
  if (res?.data) {
    totalDemandList.value = res.data;
  } else {
    totalDemandList.value = [];
  }
};
const getLineData = async (lineType) => {
  const params = {
    stationId: props.stationInfo.id,
    lineType: lineType === 10 ? 3 : lineType, // 1-总功率 2-储能功率 3-用户功率 4-SOC 5-计量点总功率 6-计量点储能功率
    date: lineType === 10 ? form.value.date2 : form.value.date1,
  };
  const res = await $api.powerCurve(params, chartType.value);
  if (res?.data) {
    // 处理需量数据
    const processedData = res.data.map((item) => {
      const matchedDemand = linkDemandList.value.find(
        (demand) => demand.deviceId === item.linkId
      );
      return {
        ...item,
        demand: matchedDemand ? matchedDemand.demand : "未设置需量",
      };
    });
    //总需量处理数据
    const processedDataFnal = processedData.map((item) => {
      const matchedTotalDemand = totalDemandList.value.find(
        (demand) => demand.deviceId === item.linkId
      );
      return {
        ...item,
        totaldemand: matchedTotalDemand
          ? matchedTotalDemand.totalDemand
          : "未设置总需量",
      };
    });
    chartsTableData.value.push(res.data);
    return processedDataFnal.sort((a, b) => a.linkId - b.linkId);
  } else {
    return null;
  }
};
const branchData = ref([]); // 存放支路关口表维度数据
const getPowerChartData = async () => {
  max2 = [];
  maxNum = null;
  chartsData.value = [];
  chartsTableData.value = [];
  chartOptionData.value = cloneDeep(chartOption);
  pointChartOptionData.value = cloneDeep(pointChartOption);
  if (!form.value.date1) {
    message.error("请选择日期");
    return;
  }
  let lineType = ref([]);
  if (chartType.value !== "point") {
    lineType = [1, 2, 3, 4]; // 1-总功率 2-储能功率 3-用户功率 4-SOC 5-计量点总功率 6-计量点储能功率 7-充电枪功率
    if (form.value.date2) {
      lineType.push(10); // 如果选择了第二个日期，添加第二条用户功率曲线
      chartOptionData.value.series.push(userChartOption);

      chartOptionData.value.series[4].name = `${form.value.date2}用户功率`;
    } else {
      chartOptionData.value.series = chartOptionData.value.series.filter(
        (item) => !item.userChartOption
      );
    }
    chartOptionData.value.series[2].name = `${form.value.date1}用户功率`;

    // 以下进入支路关口表逻辑，只有功率曲线才会请求支路关口表
    if (chartType.value === "normal") {
      if (props.stationInfo.isChargeProject) {
        // lineType = [1, 2, 3, 4, 7];
        lineType.push(7)
      }
      const branchRes = await $api.powerCurveBranch(props.stationInfo.id);
      if (branchRes?.data?.length) {
        branchData.value = branchRes.data;
        // 如果有支路关口表
        for (const item of branchRes.data) {
          if (!chartOptionData.value.series?.[item.type - 1]) {
            chartOptionData.value.series[item.type - 1] = {}; // 初始化为空对象
          }
          const chartsOption = cloneDeep(brandChartOption);
          chartsOption.name = item.name;
          chartOptionData.value.series[item.type - 1] = chartsOption;
        }
        lineType.push(...branchRes.data.map((item) => item.type));
      }
    }
  } else {
    lineType = [5, 6];
  }

  chartLoading.value = true;
  const promises = lineType.map((types) => getLineData(types));
  await Promise.all(promises).then(async (resList) => {
    const res = resList.filter((item) => item);
    const processCharts = async (chartArray, optionData, chartVar) => {
      const groupedById = {};
      chartsData.value = res[0];

      res.flat().forEach((item) => {
        if (chartType.value !== "point") {
          if (!groupedById[item.stationTfId]) {
            groupedById[item.stationTfId] = [];
          }
          groupedById[item.stationTfId].push(item);
        } else {
          if (!groupedById[item.linkId]) {
            groupedById[item.linkId] = [];
          }
          groupedById[item.linkId].push(item);
        }
      });
      const resultArray = Object.values(groupedById);
      resultArray.forEach((item, index) => {
        chartArray[index] = cloneDeep(optionData.value);
        // 处理充电枪数据
        const chargingGunData = item.filter((data) => data.lineType === 7);
        if (chargingGunData.length > 0) {
          // 为每个充电枪数据创建新的 series
          chargingGunData.forEach((gunData, gunIndex) => {
            const newSeries = cloneDeep(brandChartOption);
            newSeries.name = gunData.lineName || `充电枪${gunIndex + 1}`;
            chartArray[index].series.push(newSeries);
          });
        }
        item.forEach((chartData, chartIndex) => {
          if (chartData.lineType === 7) {
            // 对于充电枪数据，找到对应的 series 并设置数据
            const seriesIndex = chartArray[index].series.findIndex(
              (series) =>
                series.name ===
                (chartData.lineName || `充电枪${chartIndex + 1}`)
            );
            if (seriesIndex !== -1) {
              chartArray[index].series[seriesIndex].data =
                chartData.lineData.map((item) => {
                  const value = Number(item.value);
                  // 将充电枪功率数据的值也加入到max2数组中，用于计算Y轴最大值
                  if (!isNaN(value)) {
                    max2.push(value);
                  }
                  return {
                    ...item,
                    value: value,
                  };
                });
            }
          } else {
            if (
              chartData.date === form.value.date2 &&
              chartData.lineType === 3
            ) {
              initChart(chartData, index, 10);
            } else {
              initChart(chartData, index, chartData.lineType);
            }
          }
        });
        if (chartType.value !== "point") {
          maxNum = max2.length > 0 ? Math.max(...max2) : 0;
          // 重新处理需量
          item.forEach((chartData) => {
            if (chartData.lineType !== 7) {
              processChartDemand(chartData, chartArray[index], maxNum, max2);
            }
          });
        } else {
          maxNum = max2.length > 0 ? Math.max(...max2) : 0;
          // 重新处理总需量
          item.forEach((chartData) => {
            if (chartData.lineType !== 7) {
              processChartTotalDemand(
                chartData,
                chartArray[index],
                maxNum,
                max2
              );
            }
          });
        }
      });

      await nextTick();
      chartArray.forEach((chartOption, index) => {
        const chartEl = document.getElementById("powerChart" + index);
        if (chartEl) {
          const chartInstance = echarts.init(chartEl);
          chartInstance.resize();
          chartInstance.clear();
          chartInstance.setOption(chartOption);
        }
      });
    };
    if (chartType.value !== "point") {
      await processCharts(powerChart.value, chartOptionData, "powerChart");
    } else {
      await processCharts(pointChart.value, pointChartOptionData, "pointChart");
    }
    chartLoading.value = false;
  });
};
const checkData = () => {
  detailsDataVisible.value = true;
};
onMounted(() => {});
const handleChageStation = () => {
  form.value.date1 = getCurrentDate();
  chartType.value = "normal";
  getDemand();

  getPowerChartData();
  checkPoint();
};
const changeChartType = () => {
  // getPowerChartData()
};
defineExpose({ handleChageStation });
</script>

<style lang="less" scoped>
.chartForm {
  margin-top: 20px;
}
.ant-form-item {
  margin-bottom: 20px;
}
.chartContainer {
  margin-bottom: 20px;
  width: 100%;
  height: 640px;
  background: #141414;
  border-radius: 4px;
}
.filterBtn {
  margin-right: 20px;
}
</style>
